package com.example.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bw.itext.pdf.service.PdfService;
import com.example.conf.AlipayConfig;
import com.example.domain.Order;
import com.example.domain.Product;
import com.example.service.OrderService;
import com.example.service.ProductService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.SneakyThrows;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.UUID;

/**
 * @className: OrderController
 * @author: Joe
 * @create: 2023-02-07 12:59
 * @description:订单相关操作
 */
@CrossOrigin
@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    OrderService orderService;
    @Autowired
    ProductService productService;
    @Autowired
    PdfService pdfService;
    @Autowired
    RocketMQTemplate rocketMqTemplate;

    /**
     * 创建订单的同时也创建进行支付
     * @param order
     * @return
     */
    @RequestMapping("/createOrder")
    public Boolean create(@RequestBody Order order){
        order.setCreated(new Date());
        //在添加订单成功后再去支付
        return orderService.save(order);
    }

    /**
     * 支付回调
     * 首先回调需要修改订单和相对应的产品的状态
     * 说明这个产品只有一个且只能购买一次
     * 先根据UUId最后一个产品的id获取该产品
     * 然后再通过产品名称去订单表寻找相应的订单数据
     * excel表导出
     * pdf导出
     * 电子签章
     */
    @SneakyThrows
    //@GlobalTransactional(rollbackFor = Exception.class)
    @RequestMapping("/ret")
    public void ret(String out_trade_no, HttpServletResponse response){
        setExcelRespProp(response,"订单导出");
        String[] split = out_trade_no.split("-");
        String str=split[split.length-1];
        Product byId = productService.getById(str);
        byId.setState(1);
        //修改产品状态
        boolean b = productService.updateById(byId);
        //修改成功后再去订单查询修改状态
        if (b){
            QueryWrapper<Order> wrapper = new QueryWrapper<>();
            wrapper.eq("state",0);
            wrapper.eq("name",byId.getName());
            Order one = orderService.getOne(wrapper);
            one.setState(1);
            //修改该订单的状态为已支付
            orderService.updateById(one);
            //发送mq消息
            //pdf导出
            pdfService.export(orderService.list(),"order.pdf","导出pdf", Order.class);
            //电子签章
            //pdfService.sign("order.pdf","order-sign.pdf");
            EasyExcel.write(response.getOutputStream())
                    .head(Order.class)
                    .sheet("订单列表")
                    .doWrite(orderService.list());
            //重定向到列表
        }
    }
    /**
     * 设置excel下载响应头属性
     */
    private void setExcelRespProp(HttpServletResponse response, String rawFileName) throws UnsupportedEncodingException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode(rawFileName, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
    }
    /**
     * 阿里云支付宝支付
     * @param id
     * @param price
     * @return
     */
    @RequestMapping("/pay")
    public String  pay(String id,String price,String name) {

        // 商户订单号，商户网站订单系统中唯一订单号，必填
        // 订单名称，必填
        // 付款金额，必填
        // 商品描述，可空
        // 超时时间 可空
        String timeout_express = "2m";
        // 销售产品码 必填
        String product_code = "QUICK_WAP_WAY";
        // SDK 公共请求类，包含公共请求参数，以及封装了签名与验签，开发者无需关注签名与验签
        //调用RSA签名方式
        AlipayClient client = new DefaultAlipayClient(AlipayConfig.URL,AlipayConfig.APPID, AlipayConfig.RSA_PRIVATE_KEY, AlipayConfig.FORMAT, AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.SIGNTYPE);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        AlipayTradePagePayModel model = new AlipayTradePagePayModel();
        model.setOutTradeNo(UUID.randomUUID()+"-"+id);
        model.setTotalAmount(price);
        model.setSubject("支付"+name+"的支付订单");
        model.setProductCode("FAST_INSTANT_TRADE_PAY");
        request.setBizModel(model);
        request.setReturnUrl(AlipayConfig.return_url);
        AlipayTradePagePayResponse alipayTradePagePayResponse = null;
        try {
            alipayTradePagePayResponse = client.pageExecute(request);
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        if (alipayTradePagePayResponse.isSuccess()) {
            return alipayTradePagePayResponse.getBody();
        } else {
            System.out.println("调用失败");
            return null;
        }
    }
}
